import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
// 懒加载
export const lazyLoadingFn = (fnAPI) => {
  const target = ref(null)
  const data = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        fnAPI().then(res => {
          data.value = res.result
        })
      }
    },
    { threshold: [0] }
  )
  return {
    target,
    data
  }
}

// 节流函数
export const _debonce = (func, wait, immediate) => {
  let timeout, result;
  if (typeof func !== 'function') {
    throw new TypeError('expected a function')
  }
  const debounced = function () {
    const _this = this;
    const args = arguments;

    if (timeout) clearTimeout(timeout);

    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(function () {
        timeout = null;
      }, wait)
      if (callNow) {
        result = func.apply(_this, args);
      }
    } else {
      timeout = setTimeout(function () {
        func.apply(_this, args)
      }, wait)
    }
    return result;
  }
  return debounced;
}
